import {
    EntityDieAfterEvent,
    GameMode,
    Player,
    PlayerSpawnAfterEvent,
    world,
} from "@minecraft/server";
import { GameComponent } from "@sapi-game/main";
import { PillarOFFortunePlayer } from "../module";
import { PillarOfFortuneMainState } from "../states/mainState";
import { PillarOfFortuneDamage } from "./damage";

export class PillarOfFortuneRespawn extends GameComponent<PillarOfFortuneMainState> {
    override onAttach(): void {
        this.subscribe(
            world.afterEvents.playerSpawn,
            this.onPlayerSpawn.bind(this)
        );
        this.subscribe(
            world.afterEvents.entityDie,
            this.onEntityDie.bind(this)
        );
    }
    /**
     * 玩家重生事件
     */
    private onPlayerSpawn(event: PlayerSpawnAfterEvent) {
        const player = event.player;
        const gamePlayer = this.context.players.getById(player.id);
        if (!gamePlayer) return;
        gamePlayer.player?.setGameMode(GameMode.Spectator);
        if (!gamePlayer.alive) return;

        // 查找击杀来源
        const source = this.getKillSource(gamePlayer);
        this.broadcastKillMessage(gamePlayer, source);

        // 标记为死亡状态并切换观察者模式
        gamePlayer.alive = false;
        gamePlayer.player?.setGameMode(GameMode.Spectator);
    }

    /**
     * 实体死亡事件（包括玩家）
     */
    private onEntityDie(event: EntityDieAfterEvent) {
        const dead = event.deadEntity;
        if (!(dead instanceof Player)) return;

        const gamePlayer = this.context.players.getById(dead.id);
        if (!gamePlayer || !gamePlayer.isValid) return;

        gamePlayer.alive = false;

        // 优先使用直接伤害来源
        const damageEntity = event.damageSource?.damagingEntity;
        const killer =
            damageEntity instanceof Player
                ? this.context.players.getById(damageEntity.id)
                : this.getKillSource(gamePlayer);

        this.broadcastKillMessage(gamePlayer, killer);
    }

    /**
     * 查找击杀来源（通过伤害组件）
     */
    private getKillSource(gamePlayer: PillarOFFortunePlayer) {
        return this.state
            .getComponent(PillarOfFortuneDamage)
            ?.getSource(gamePlayer);
    }

    /**
     * 广播击杀消息
     */
    private broadcastKillMessage(
        victim: PillarOFFortunePlayer,
        killer?: PillarOFFortunePlayer
    ) {
        const message = killer
            ? `${victim.name} 被 ${killer.name} 杀了`
            : `${victim.name} 寄了`;
        this.context.players.sendMessage(message);
    }
}
